import sinon from 'sinon'
import * as step from '@flow-step/step-toolkit'
import { expect } from 'chai';
import {deleteBranchWithFilter} from '../src/deleteBranchWithFilter'


describe('deleteBranchWithFilter', () => {
    let envStub: sinon.SinonStub;
    let deleteBranchStub: sinon.SinonStub;
    let git: any;

    let stepInfoStub: sinon.SinonStub;
    beforeEach(() => {
        deleteBranchStub = sinon.stub(require('../src/deleteBranch'), 'deleteBranch');
        envStub = sinon.stub(process, 'env');
        stepInfoStub = sinon.stub(step, 'info');
        git = {
            push: sinon.stub().resolves()
        }
    });

    afterEach(() => {
        sinon.restore();
    });

    it('should delete branch if DELETE_MATCHED_BRANCH is true and the branch matches the filter', async () => {
        const filter = '^feature/'
        envStub.value({
            DELETE_MATCHED_BRANCH: 'true',
            BRANCH_FILTER: filter
        });
        const currentBranch = 'feature/testBranch'
        await deleteBranchWithFilter(git, currentBranch);
        expect(deleteBranchStub.called).to.be.true;
        expect(deleteBranchStub.calledWith(git, 'feature/testBranch')).to.be.true;
        expect(stepInfoStub.calledWith(`Deleting branch ${currentBranch} which matches the filter ${filter}`)).to.be.true;
    });


    it('should skip deleting if DELETE_MATCHED_BRANCH is true and the branch does not match the filter', async () => {
        envStub.value({
            DELETE_MATCHED_BRANCH: 'true',
            BRANCH_FILTER: '^feature/'
        });

        await deleteBranchWithFilter(git, 'bugfix/testBranch');
        expect(deleteBranchStub.notCalled).to.be.true;
        expect(stepInfoStub.calledWith(`Branch bugfix/testBranch does not match the filter ${process.env.BRANCH_FILTER}, skip deleting.`)).to.be.true;
    });

    it('should delete the branch when DELETE_MATCHED_BRANCH is false', async () => {
        envStub.value({
            DELETE_MATCHED_BRANCH: 'false'
        });

        const currentBranch = 'feature/testBranch';

        await deleteBranchWithFilter(git, currentBranch);

        expect(deleteBranchStub.called).to.be.true;
        expect(stepInfoStub.calledWith(`Deleting branch ${currentBranch} without filter`)).to.be.true;
    });

    it('should not delete the branch when BRANCH_FILTER is empty', async () => {
        envStub.value({
            DELETE_MATCHED_BRANCH: 'true',
            BRANCH_FILTER: ''
        });

        const currentBranch = 'feature/testBranch';

        await deleteBranchWithFilter(git, currentBranch);

        expect(deleteBranchStub.notCalled).to.be.true;
        expect(stepInfoStub.calledWith(`Branch ${currentBranch} does not match the filter , skip deleting.`)).to.be.true;
    });

});